<template>
  <div class="dynamic-form-demo">
    <h1>DynamicForm 动态表单演示</h1>
    
    <!-- 表单类型选择 -->
    <div class="form-type-selector">
      <a-radio-group v-model:value="currentFormType" @change="handleFormTypeChange">
        <a-radio-button value="basic">基础表单</a-radio-button>
        <a-radio-button value="complex">复杂表单</a-radio-button>
        <a-radio-button value="logistics">物流订单</a-radio-button>
      </a-radio-group>
    </div>

    <!-- 表单配置 -->
    <div class="form-config">
      <a-card title="表单配置" size="small">
        <a-space>
          <a-checkbox v-model:checked="formConfig.showActions">显示操作按钮</a-checkbox>
          <a-checkbox v-model:checked="formConfig.disabled">禁用表单</a-checkbox>
          <a-checkbox v-model:checked="formConfig.readonly">只读模式</a-checkbox>
        </a-space>
      </a-card>
    </div>

    <!-- 动态表单 -->
    <div class="form-container">
      <a-card :title="getFormTitle()" size="default">
        <DynamicForm
          ref="dynamicFormRef"
          :schema="currentSchema"
          :model="formData"
          :config="formConfig"
          :disabled="formConfig.disabled"
          :readonly="formConfig.readonly"
          :show-actions="formConfig.showActions"
          @submit="handleSubmit"
          @change="handleChange"
          @reset="handleReset"
          @validate="handleValidate"
        >
          <template #actions="{ form }">
            <a-space>
              <a-button type="primary" @click="form.submit()">提交</a-button>
              <a-button @click="form.reset()">重置</a-button>
              <a-button @click="handleValidateForm">验证</a-button>
              <a-button @click="handleSetValues">设置值</a-button>
              <a-button @click="handleGetValues">获取值</a-button>
            </a-space>
          </template>
        </DynamicForm>
      </a-card>
    </div>

    <!-- 表单数据展示 -->
    <div class="form-data-display">
      <a-card title="表单数据" size="small">
        <a-tabs v-model:activeKey="activeTab">
          <a-tab-pane key="current" tab="当前数据">
            <pre>{{ JSON.stringify(formData, null, 2) }}</pre>
          </a-tab-pane>
          <a-tab-pane key="schema" tab="表单配置">
            <pre>{{ JSON.stringify(currentSchema, null, 2) }}</pre>
          </a-tab-pane>
          <a-tab-pane key="events" tab="事件日志">
            <div class="event-log">
              <div v-for="(event, index) in eventLog" :key="index" class="event-item">
                <span class="event-time">{{ event.time }}</span>
                <span class="event-type">{{ event.type }}</span>
                <span class="event-data">{{ event.data }}</span>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import DynamicForm from './DynamicForm.vue'
import { 
  basicFormSchema, 
  complexFormSchema, 
  userInfoSchema, 
  formConfig as defaultFormConfig 
} from './example.js'

// 响应式数据
const currentFormType = ref('basic')
const formData = reactive({})
const activeTab = ref('current')
const eventLog = ref([])
const dynamicFormRef = ref()

// 表单配置
const formConfig = reactive({
  ...defaultFormConfig,
  showActions: true,
  disabled: false,
  readonly: false
})

// 当前表单配置
const currentSchema = ref(basicFormSchema)

// 获取表单标题
const getFormTitle = () => {
  const titles = {
    basic: '基础表单演示',
    complex: '复杂表单演示（包含联动）',
    logistics: '用户信息表单演示'
  }
  return titles[currentFormType.value]
}

// 处理表单类型变化
const handleFormTypeChange = (e) => {
  const type = e.target.value
  currentFormType.value = type
  
  // 切换表单配置
  switch (type) {
    case 'basic':
      currentSchema.value = basicFormSchema
      break
    case 'complex':
      currentSchema.value = complexFormSchema
      break
    case 'logistics':
      currentSchema.value = userInfoSchema
      break
  }
  
  // 清空表单数据
  Object.keys(formData).forEach(key => delete formData[key])
  
  // 记录事件
  addEventLog('formTypeChange', `切换到${getFormTitle()}`)
}

// 处理表单提交
const handleSubmit = (values) => {
  message.success('表单提交成功！')
  addEventLog('submit', values)
  console.log('表单提交数据:', values)
}

// 处理表单数据变化
const handleChange = (model) => {
  addEventLog('change', model)
  console.log('表单数据变化:', model)
}

// 处理表单重置
const handleReset = (model) => {
  message.info('表单已重置')
  addEventLog('reset', model)
  console.log('表单重置:', model)
}

// 处理表单验证
const handleValidate = (valid, errors) => {
  if (valid) {
    message.success('表单验证通过')
  } else {
    message.error('表单验证失败')
  }
  addEventLog('validate', { valid, errors })
  console.log('表单验证结果:', { valid, errors })
}

// 手动验证表单
const handleValidateForm = async () => {
  if (dynamicFormRef.value) {
    const result = await dynamicFormRef.value.validate()
    console.log('手动验证结果:', result)
  }
}

// 设置表单值
const handleSetValues = () => {
  if (dynamicFormRef.value) {
    const values = {
      name: '张三',
      gender: 'male',
      birthday: '1990-01-01',
      description: '这是一个测试数据'
    }
    dynamicFormRef.value.setFieldsValue(values)
    message.success('已设置表单值')
    addEventLog('setValues', values)
  }
}

// 获取表单值
const handleGetValues = () => {
  if (dynamicFormRef.value) {
    const values = dynamicFormRef.value.getFieldsValue()
    message.info('已获取表单值')
    addEventLog('getValues', values)
    console.log('表单当前值:', values)
  }
}

// 添加事件日志
const addEventLog = (type, data) => {
  const time = new Date().toLocaleTimeString()
  eventLog.value.unshift({
    time,
    type,
    data: typeof data === 'object' ? JSON.stringify(data, null, 2) : data
  })
  
  // 限制日志数量
  if (eventLog.value.length > 50) {
    eventLog.value = eventLog.value.slice(0, 50)
  }
}

// 组件挂载
onMounted(() => {
  addEventLog('mounted', '组件已挂载')
})
</script>

<style scoped>
.dynamic-form-demo {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.dynamic-form-demo h1 {
  text-align: center;
  margin-bottom: 20px;
  color: #1890ff;
}

.form-type-selector {
  margin-bottom: 20px;
  text-align: center;
}

.form-config {
  margin-bottom: 20px;
}

.form-container {
  margin-bottom: 20px;
}

.form-data-display {
  margin-bottom: 20px;
}

.form-data-display pre {
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  overflow-x: auto;
}

.event-log {
  max-height: 300px;
  overflow-y: auto;
}

.event-item {
  display: flex;
  gap: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  font-size: 12px;
}

.event-time {
  color: #999;
  min-width: 80px;
}

.event-type {
  color: #1890ff;
  font-weight: bold;
  min-width: 80px;
}

.event-data {
  color: #333;
  flex: 1;
  word-break: break-all;
}

:deep(.ant-card-head-title) {
  font-weight: bold;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}
</style> 